package org.mspring.platform.utils;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @since Jun 25, 2011 www.mspring.org
 * @author gaoyoubo
 */
public class HTMLUtils {

    private static final Logger log = LoggerFactory.getLogger(HTMLUtils.class);

    private static final String ENC_UTF_8 = "UTF-8";

    /**
     * 过滤掉html标记
     *
     * @param html
     *            HTML内容
     * @return 处理后的字符串。
     */
    public static String getHtmlText(String html) {
        return getHtmlText(html, ENC_UTF_8);
    }

    /**
     * 过滤掉HTML标记
     *
     * @param html
     *            HTML内容
     * @param encoding
     *            编码
     * @return
     */
    public static String getHtmlText(String html, String encoding) {
        if (html != null) {
            StringBuilder str = new StringBuilder();
            try {
                Parser parser = Parser.createParser(html, encoding);
                // 注册自定义的新结点解析器,这是必要的...
                // factory(parser);
                NodeList nodelist = parser.extractAllNodesThatMatch(new NodeFilter() {
                    private static final long serialVersionUID = 3428661795844912771L;

                    @Override
                    public boolean accept(Node node) {
                        return node instanceof TextNode;
                    }
                });
                for (int i = 0; i < nodelist.size(); i++) {
                    TextNode t = (TextNode) nodelist.elementAt(i);
                    str.append(t.toPlainTextString());
                }
                return str.toString();
            } catch (ParserException e) {
                log.error(e.getMessage(), e);
                return null;
            }
        } else {
            return null;
        }
    }

    public static final String autoformat(String s) {
        String ret = StringUtils.replace(s, "\n", "<br />");
        return ret;
    }

    public static final String escapeHTML(String s) {
        return StringEscapeUtils.escapeHtml4(s);
    }

}
